#!/bin/bash

###
### This file is part of icecode-project.
###
###    icecode-project is free software: you can redistribute it and/or modify
###    it under the terms of the GNU General Public License as published by
###    the Free Software Foundation, either version 3 of the License, or
###    (at your option) any later version.
###
###    icecode-project is distributed in the hope that it will be useful,
###    but WITHOUT ANY WARRANTY; without even the implied warranty of
###    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
###    GNU General Public License for more details.
###
###    You should have received a copy of the GNU General Public License
###    along with icecode-project.  If not, see <http://www.gnu.org/licenses/>.
###
###    Copyright 2012 Alfredo Mungo
###


. meta/common.sh

src_dir="!!SOURCE!!"
src_ext=( !!EXTENSIONS!! )

# Each file should end with the '.in' extension
infiles=( Makefile.in \
    "$src_dir/version.hpp.in" \
    !!PKGCONFIGINFILE!! \
    LICENSE.template.in ) # Add custom '.in' files here

grep_cmd="grep"
i=0
while [[ ! -z ${src_ext[$i]} ]]; do
    grep_cmd="$grep_cmd -e '\.${src_ext[$i]}'"
done


# updateFile (filename_in, filename) : void
# Update 'filename' on the basis of the model 'filename_in'
function updateFile ()
{
    infname=$1
    fname=$2

    sed -e "s:@@OBJECTS@@:$objects:g" \
	-e "s:@@MAJOR@@:$v_major:g" \
	-e "s:@@MINOR@@:$v_minor:g" \
	-e "s:@@PHASE@@:$v_phase:g" \
	-e "s:@@PROGNAME@@:$progname:g" \
        -e "s:@@LIBNAME@@:$progname:g" \
        -e "s:@@DESCRIPTION@@:$description:g" \
        -e "s:@@PROJECT@@:$project:g" \
        -e "s:@@AUTHOR@@:$author:g" \
        -e "s:@@RELEASES@@:$releases:g" \
        -e "s:@@CFLAGS@@:$cflags:g" \
        -e "s:@@LIBS@@:$libs:g" \
        -e "s:@@PRIVLIBS@@:$privlibs:g" \
        -e "s:@@REQUIRES@@:$requires:g" \
	$infname > $fname
}

## Update variables
objects=
for line in `find $src_dir/ -type f | $grep_cmd`; do
    if [[ -z "$objects" ]]; then
	objects=$(echo "$line" | sed -e "s:.+\.cpp\$:.o:" -e "s:.+\.c\$:.o:")
    else
	objects="$objects $(echo "$line" | sed -e 's:.+\.cpp$:.o:' -e 's:.+\.c$:.o:')"
    fi
done

declare -a version
i=0
for a in $(< meta/VERSION); do
    version[$i]=$a
    ((i++))
done

progname=${version[0]}
v_major=${version[1]}
v_minor=${version[2]}
v_phase=${version[3]}
unset version

description=$(< meta/DESCRIPTION)
project=$(< meta/PROJECT)
author=$(< meta/AUTHOR)
releases=$(< meta/RELEASES)
libs=$(< meta/LIBS)
privlibs=$(< meta/LIBS.PRIVATE)
cflags=$(< meta/CFLAGS)
requires=$(< meta/REQUIRES)

## Update files
i=0
while [[ ! -z ${infiles[$i]} ]]; do
    infname=${infiles[$i]}
    fname=`echo -n $infname | sed 's:\.in$::'`
    if [[ $fname -ot $infname ]]; then
	echo -e "Updating file \033[32m$fname\033[0m..."
	updateFile $infname $fname
    else
	echo -e "Skipping file \033[31m$fname\033[0m..."
    fi
    ((i++))
done
